package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.BookDaoImp;
import com.atguigu.dao.impl.OrderDaoImp;
import com.atguigu.dao.impl.OrderItemDaoImp;
import com.atguigu.pojo.*;
import com.atguigu.service.OrderService;

import java.util.Date;
import java.util.Map;

/**
 * @author Chen
 * @Description
 * @Version
 * @create 2021-11-21-14:32
 */
public class OrderServiceImp implements OrderService {
    private OrderDao orderDao = new OrderDaoImp();
    private OrderItemDao orderItemDao = new OrderItemDaoImp();
    private BookDao bookDao = new BookDaoImp();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        String orderId = System.currentTimeMillis() + "" + userId;

        Order order = new Order(orderId, new Date(), cart.getTotalPrice(),0 , userId);
        orderDao.saveOrder(order);


//        遍历购物车总的每一商品项转换成订单项保存到数据库中
        for(Map.Entry<Integer, CartItem>entry : cart.getItems().entrySet()){
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            orderItemDao.saveOrderItem(orderItem);
            Book book = bookDao.queryBookById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookDao.updateBook(book);
        }
        cart.clear();

        return orderId;
    }
}
